package com.iplus.ydkf.ehome.module.home;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSONObject;
import com.iplus.ydkf.ehome.App;
import com.iplus.ydkf.ehome.R;
import com.iplus.ydkf.ehome.common.net.Callback;
import com.iplus.ydkf.ehome.common.net.JsonParser;
import com.iplus.ydkf.ehome.common.net.JsonRequestBody;
import com.iplus.ydkf.ehome.common.net.NetClient;
import com.iplus.ydkf.ehome.common.net.StringParser;
import com.iplus.ydkf.ehome.common.utils.DateUtil;
import com.iplus.ydkf.ehome.common.views.CircleImageView;
import com.iplus.ydkf.ehome.config.ConString;
import com.iplus.ydkf.ehome.module.base.BaseFragment;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.RequestBody;

/**
 * Created by liuhaitian on 16/5/8.
 */
public class IndexFragment extends BaseFragment implements MaterialDialog.SingleButtonCallback {
    @Bind(R.id.tv_index_state)
    TextView tv_state;
    @Bind(R.id.tv_index_location)
    TextView tv_location;
    @Bind(R.id.tv_index_temperture)
    TextView tv_temerture;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    SingleAdapter adapter;
    App app;
    private JSONObject roomObject = new JSONObject();
    private int roomPosition = 0;
    private int[] icon_uris = {R.drawable.room_1, R.drawable.room_2, R.drawable.room_3, R.drawable.room_4, R
            .drawable.room_5};
    private static IndexFragment fragment;

    public static IndexFragment getInstance() {
        if (fragment == null)
            fragment = new IndexFragment();
        return fragment;
    }

    @Override
    public int bindLayout() {
        return R.layout.fragment_index;
    }

    @Override
    public void initView(View view) {
        app = (App) getActivity().getApplication();
        tv_state.setText(DateUtil.getCurrentAmOrPm());
        tv_location.setText(app.getCity());
        adapter = new SingleAdapter();
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onResume() {
        super.onResume();
        getRoom();
    }

    @Override
    public void initData(View view) {
        getWeather();
    }

    @Override
    public String getFragmentName() {
        return "首页";
    }

    public void getWeather() {
        Map<String, String> header = new HashMap<>();
        Map<String, String> city = new HashMap<>();
        city.put("cityname", app.getCity());
        header.put("apikey", "41774a6f395cb3cd21d52ddb1299859c");
        StringParser parser = new StringParser();
        NetClient.sendGetRequest(ConString.WEATHER_INFO, new Callback<JSONObject>(JsonParser.getInstance()) {

            @Override
            public void onResponse(JSONObject jsonObject) {
                if (jsonObject.getIntValue("errNum") == 0) {
                    JSONObject result = jsonObject.getJSONObject("retData");
                    logd(result.toJSONString());
                    tv_temerture.setText(result.getIntValue("l_tmp") + "/" + result.getIntValue("h_tmp") + "°c");
                }
            }

            @Override
            public void onFailure(IOException e) {

            }
        }, header, city);
    }

    public void getRoom() {
        Map<String, String> header = new HashMap<>();
        header.put("userId", App.getCurrentUser().getObjectId());
        NetClient.sendGetRequest(ConString.CLOUD_ROOM, new Callback<JSONObject>(JsonParser.getInstance()) {
            @Override
            public void onResponse(JSONObject jsonObject) {
                roomObject = jsonObject;
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(IOException e) {

            }
        }, header);
    }

    @Override
    protected void lazyLoad() {

    }


    public class SingleAdapter extends RecyclerView.Adapter<SingleAdapter.ViewHolder> {


        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = View.inflate(getActivity(), R.layout.item_index, null);
            view.setOnClickListener(new MyOnClickListener());
            view.setOnLongClickListener(new MyOnLongClickListener());
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            if (position == getItemCount() - 1) {
                holder.imageView.setImageResource(R.drawable.icon_addroom);
                holder.tv_roomname.setText(" ");
                holder.layout_roominfo.setVisibility(View.GONE);
                holder.tv_addRoom.setVisibility(View.VISIBLE);
                return;
            }
            JSONObject room = roomObject.getJSONArray("data").getJSONObject(position);
            holder.tv_addRoom.setVisibility(View.GONE);
            holder.layout_roominfo.setVisibility(View.VISIBLE);
            holder.tv_deviceNumber.setText(room.getIntValue("devicesCount") + "");
            holder.tv_roomname.setText(room.getString("roomName"));
            String pic = room.getString("roomPic");
            holder.imageView.setImageResource(icon_uris[Integer.valueOf(pic) - 1]);
        }

        @Override
        public int getItemCount() {
            if (!roomObject.containsKey("data"))
                return 1;
            else return roomObject.getJSONArray("data").size() + 1;
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            @Bind(R.id.iv_item_room)
            CircleImageView imageView;
            @Bind(R.id.tv_item_addRoom)
            TextView tv_addRoom;
            @Bind(R.id.ll_item_room)
            LinearLayout layout_roominfo;
            @Bind(R.id.tv_roomitem_devicenumber)
            TextView tv_deviceNumber;
            @Bind(R.id.tv_roomitem_roomname)
            TextView tv_roomname;

            public ViewHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }

        class MyOnLongClickListener implements View.OnLongClickListener {


            @Override
            public boolean onLongClick(View v) {
                int itemPosition = recyclerView.getChildLayoutPosition(v);
                if (itemPosition != roomObject.getJSONArray("data").size()) {
                    roomPosition = itemPosition;
                    displayDeleteRoomDialog();
                }
                return false;
            }
        }

        class MyOnClickListener implements View.OnClickListener {

            @Override
            public void onClick(View v) {
                int itemPosition = recyclerView.getChildLayoutPosition(v);
                if (!roomObject.containsKey("data")) {
                    Intent intent = new Intent(getActivity(), RoomActivity.class);
                    JSONObject room = roomObject.getJSONArray("data").getJSONObject(itemPosition);
                    intent.putExtra("roomId", room.getString("roomId"));
                    intent.putExtra("roomName", room.getString("roomName"));
                    startActivity(intent);
                    return;
                }
                if (itemPosition == roomObject.getJSONArray("data").size()) {
                    displayCreateRoomDialog();
                } else {
                    Intent intent = new Intent(getActivity(), RoomActivity.class);
                    JSONObject room = roomObject.getJSONArray("data").getJSONObject(itemPosition);
                    intent.putExtra("roomId", room.getString("roomId"));
                    intent.putExtra("roomName", room.getString("roomName"));
                    startActivity(intent);
                }
            }
        }
    }

    private void displayDeleteRoomDialog() {
        new MaterialDialog.Builder(getActivity())
                .title("删除房间")
                .content("是否确认删除房间？该房间下所有设备将会不在显示在房间内")
                .neutralText("确认").onNeutral(this)
                .negativeText("取消")
                .show();
    }

    public void displayCreateRoomDialog() {
        boolean wrapInScrollView = true;
        MaterialDialog builder = new MaterialDialog.Builder(getActivity())
                .title("创建房间")
                .customView(R.layout.dialog_createroom, wrapInScrollView)
                .positiveText("创建").onPositive(this)
                .negativeText("取消").onNegative(this)
                .build();
        final View view = builder.getCustomView();
        final CircleImageView sdv = (CircleImageView) view.findViewById(R.id.sdv_dialog_roomPic);
        sdv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final MaterialDialog builder = new MaterialDialog.Builder(getActivity())
                        .title("选择图片")
                        .customView(R.layout.dialog_choise_room, true)
                        .negativeText("返回").onNegative(IndexFragment.this)
                        .build();
                View view1 = builder.getCustomView();
                GridView gv = (GridView) view1.findViewById(R.id.gv_dialog_choiseroom);
                gv.setAdapter(new MyAdapter());
                gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        sdv.setImageResource(icon_uris[position]);
                        sdv.setTag(position + 1);
                        builder.dismiss();
                    }
                });
                builder.show();
            }
        });
        builder.show();
    }

    @Override
    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
        if (which == DialogAction.POSITIVE) {
            View view = dialog.getCustomView();
            CircleImageView sdv = (CircleImageView) view.findViewById(R.id.sdv_dialog_roomPic);
            EditText et = (EditText) view.findViewById(R.id.et_dialog_roomname);
            if (sdv.getTag() == null) {
                snackbar("请选择图片");
                return;
            }
            if (TextUtils.isEmpty(et.getText().toString())) {
                snackbar("请输入房间名");
                return;
            }
            RequestBody requestBody = JsonRequestBody.create().put("roomName", et.getText().toString()).put
                    ("roomPic", sdv.getTag().toString()).build();
            NetClient.sendPostRequest(ConString.CLOUD_ROOM, requestBody, new Callback<JSONObject>(JsonParser
                    .getInstance()) {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    if (jsonObject.getIntValue("errorCode") == 0)
                        snackbar("创建成功");
                    getRoom();
                }

                @Override
                public void onFailure(IOException e) {

                }
            });
        }
        if (which == DialogAction.NEUTRAL) {
            String roomid = roomObject.getJSONArray("data").getJSONObject(roomPosition).getString("roomId");
            NetClient.sendDelRequest(ConString.CLOUD_ROOM + "/" + roomid, new Callback<JSONObject>(JsonParser.getInstance()) {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    if (jsonObject.getIntValue("errorCode") == 0) {
                        snackbar("删除成功");
                        getRoom();
                    } else snackbar("删除失败，原因" + jsonObject.getString("errorMsg"));
                }

                @Override
                public void onFailure(IOException e) {

                }
            });
        } else {
            dialog.dismiss();
        }
    }

    public class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return icon_uris.length;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView = new ImageView(getActivity());
            imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            imageView.setBackgroundResource(icon_uris[position]);
            return imageView;
        }
    }

}
